<?php
/**
 * Created by KLXQ
 * user: youyi
 * Date：2024/6/6  10:35.
 * Tencent ROOM SDK.
 * 目前主要用于判断房间是否存在.
 */

namespace App\Http\Helpers\Tencent;

use App\Services\TencentRequestService;
use Illuminate\Support\Facades\Log;
use Random\RandomException;

class RoomTencent
{
    public const GET_ROOM_INFO = 'get_room_info';

    public string $endpoint = 'https://console.tim.qq.com/v4/room_engine_http_srv/';
    public int $sdkAppId;
    public string $identifier;
    public string $action;
    public array $resultArr = ['code' => 200, 'msg' => 'success', 'data' => []];

    /**
     * @param mixed $action
     *
     * @throws RandomException
     */
    public function __construct($action)
    {
        $this->sdkAppId = config('tencent.trtc.app_id');
        $this->identifier = config('tencent.trtc.admin');
        $this->action = $action;
        $sign = new SignTencent();
        $userSig = $sign->genUserSign($this->identifier);

        $query = [
            'sdkappid' => $this->sdkAppId,
            'identifier' => $this->identifier,
            'usersig' => $userSig,
            'random' => random_int(1, 9999),
            'contenttype' => 'json',
        ];

        $this->endpoint .= $action.'?'.http_build_query($query);
    }

    public function getRoomInfo($roomId): void
    {
        $params = [
            'RoomId' => (string) $roomId,
        ];
        $payload = json_encode($params);
        $this->httpRequest($this->endpoint, $payload);
    }

    public function httpRequest($url, $payload): void
    {
        try {
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_POST, true);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            $response = curl_exec($ch);
            curl_close($ch);

            $res = json_decode($response, true);

            Log::channel('tencent')->info('response: '.$response);

            if (0 !== $res['ErrorCode']) {
                $this->resultArr['code'] = $res['ErrorCode'];
                $this->resultArr['msg'] = $res['ErrorInfo'];
            } else {
                if (isset($res['Response'])) {
                    $this->resultArr['data'] = $res['Response'];
                }
            }
        } catch (\Exception $err) {
            $this->resultArr['code'] = -1;
            $this->resultArr['msg'] = $err->getMessage();
        }

        // 记录日志
        TencentRequestService::create('room', $this->action, $payload, $this->resultArr);
    }
}
